package com.mz361.stdapi.service.impl;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mz361.common.utils.DateUtils;
import com.mz361.common.utils.HttpServletUtil;
import com.mz361.common.utils.RedisUtil;
import com.mz361.common.utils.UploadBailianUtil;
import com.mz361.stdapi.service.AIRequestService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class AIRequestServiceImpl implements AIRequestService {
    private final static String GETCHATIDURL = "http://62.234.17.78:8600/api/get_chat_id";
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    UploadBailianUtil uploadBailianUtil;

    @Override
    public String getChatId(String userId) {
        Map<String, String> param = new HashMap<>();
        param.put("user_id", userId);
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("Authorization", "Bearer ragflow-k1YTcyMTAyNjUzMDExZWY5MjE0MDI0Mm");
        return HttpServletUtil.sendPostRequestByJson(GETCHATIDURL, JSONObject.toJSONString(param), headers);
    }

    @Override
    public void postAnswer(String userId, String chartId, String question, String answer) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("question", question);
        jsonObject.put("answer", answer);
        jsonObject.put("date", DateUtils.getCurrDate());
        redisUtil.rPush("CHART:HISTORY:" + userId + ":" + chartId, jsonObject.toJSONString());

    }

    @Override
    public JSONArray getHistory(String userId, String chartId) {
        List<String> list = redisUtil.lRange("CHART:HISTORY:" + userId + ":" + chartId, 0L, -1L);
        JSONArray jsonArray = new JSONArray();
        list.forEach((k) -> {
            jsonArray.add(JSONObject.parseObject(k));
        });
        return jsonArray;
    }

    @Override
    public String uploadImage(String imageUrl) throws Exception {
        return uploadBailianUtil.uploadBailian(imageUrl, "cate_829a4ff470324da891c4cea6bf56a3d0_10253128");
    }
}
